/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: GroupCreateAction.java,v 1.11 2006/07/15 23:13:58 nano Exp $
*/
package net.jxta.myjxta.ui.action;

import net.jxta.exception.PeerGroupException;
import net.jxta.myjxta.MyJXTA;
import net.jxta.myjxta.View;
import net.jxta.myjxta.ui.ChatFrame;
import net.jxta.myjxta.ui.GroupCreatePanel;
import net.jxta.myjxta.ui.MyJXTAView;
import net.jxta.myjxta.util.Constants;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.PeerGroupUtil;
import net.jxta.myjxta.util.Resources;
import net.jxta.peergroup.PeerGroup;
import net.jxta.protocol.PeerGroupAdvertisement;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ResourceBundle;

/**
 * @author james todd [gonzo at jxta dot org]
 * @version $Id: GroupCreateAction.java,v 1.11 2006/07/15 23:13:58 nano Exp $
 */

public class GroupCreateAction
        extends AbstractAction {

    private static final long MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;
    private static final ResourceBundle STRINGS = Resources.getStrings();

    /**
     * The View instance that constitutes the UI of this application
     */
    private View view = null;
    private MyJXTAView m_view = null;

    /**
     * The JDialog that collects the data for the new group
     */
    private JDialog dialog;

    /**
     * The GroupCreatePanel that collects the user data
     */
    private GroupCreatePanel createGroup;

    /**
     * Create a new GroupCreationAction
     *
     * @param name the descriptive name of the Action
     * @param view MyJXTAView instance that constitutes the UI
     *             of this application
     */
    public GroupCreateAction(String name, View view, MyJXTAView m_view) {
        super(name);

        this.view = view;
        this.m_view=m_view;
    }

    /**
     * Called if the user wants to create a new PeerGroup
     *
     * @param ae the triggering ActionEvent
     */
    public void actionPerformed(ActionEvent ae) {
        // xxx: shouldn't have to make this modal
        this.dialog = new JDialog((Frame) this.view,
                STRINGS.getString("title.group.create"), false);
        this.createGroup = new GroupCreatePanel();

        this.dialog.getContentPane().add(this.createGroup);
        this.dialog.pack();
        this.dialog.setLocationRelativeTo((Frame) this.view);
        this.dialog.addComponentListener(new ComponentAdapter() {
            public void componentHidden(ComponentEvent ce) {
                if (! createGroup.isCancel()) {
                    process();
                }

                dialog = null;
                createGroup = null;
            }
        });
        this.dialog.setVisible(true);
    }

    private void process() {
        // get the data the user typed in
        String name = this.createGroup.getName();
        int expiration = this.createGroup.getExpirationDays();
        String description = this.createGroup.getDescription();
        String password = this.createGroup.getPassword();
        int app=this.createGroup.getSelectedApp();

        name = name != null ? name.trim() : name;
        description = description != null &&
                description.trim().length() > 0 ?
                description.trim() : MyJXTA.VERSION;
        password = password != null ? password.trim() : "";

        if (name.length() == 0) {
            name = null;
        }

        // only create groups which have a  non-empty name
        if (name != null) {
            Group parent = ((MyJXTAView) this.view).findDeepestJoinedGroupAboveSelection();
            PeerGroup ppg = parent.getPeerGroup();
            PeerGroupAdvertisement pga = null;

            this.view.setStatus(STRINGS.getString("status.group.create") +
                    " " + name);

            // create the PeerGroupAdvertisement for the new group
            try {
                pga = PeerGroupUtil.create(ppg, name, description,
                        password, expiration * MILLISECONDS_IN_A_DAY);
                
            } catch (Exception e) {
                this.view.setStatus(STRINGS.getString("error.group.advertisement.create") +
                        " " + name);
            }

            if (pga != null) {
                PeerGroup pg = null;

                // Create the group itself
                try {
                    pg = ppg.newGroup(pga);
                } catch (PeerGroupException pge) {
                    this.view.setStatus(STRINGS.getString("error.group.create") +
                            " " + name);
                }

                // if the group was successfully created join it
                if (pg != null) {
                    Group g = new Group(this.view.getControl(), pg, parent);

                    g.setAutoRendezVousPeriod(Constants.AUTO_RENDEZVOUS_CREATE_PERIOD);

                    this.view.getControl().joinGroup(g, true, true);
                    
                    if(app==0){
                    	this.m_view.getRunButton().setEnabled(true);
                    	
                    	if(!ChatFrame.isVisible){

                    		
                    		JPanel p = new JPanel();
                            GridBagLayout gb = new GridBagLayout();
                            GridBagConstraints gbc = new GridBagConstraints();

                            p.setLayout(gb);


                            gbc.gridx = 0;
                            gbc.gridy = 0;
                            gbc.gridwidth = GridBagConstraints.REMAINDER;
//                            gbc.insets = new Insets(3, 3, 3, 3);
                            gbc.anchor = GridBagConstraints.NORTHWEST;
                            gbc.weightx = 1.0;
                            gbc.weighty = 1.0;
                            gbc.fill = GridBagConstraints.BOTH;

                            gb.setConstraints(this.m_view.plugins, gbc);
                            p.add(this.m_view.plugins);
                    		  		
                    		ChatFrame cf=new ChatFrame(p);
                            cf.setVisible(true);
                		}
                    }
                    
                } else {
                    this.view.setStatus(STRINGS.getString("error.group.create") +
                            " " + name);
                }
            } else {
                this.view.setStatus(STRINGS.getString("error.group.advertisement.create") +
                        " " + name);
            }
        }
    }

    /* (non-Javadoc)
      * @see javax.swing.Action#isEnabled()
      */
    public boolean isEnabled() {
	if (this.view instanceof MyJXTAView) {
	    return ((MyJXTAView) this.view).findDeepestJoinedGroupAboveSelection() != null;
  
	} else {
	    return false;
	}
        
    }
}
